package com.zqwh.xtool.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;

import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.SharePreferencesUtils;

import java.io.File;
import java.util.Objects;

import static android.app.DownloadManager.ACTION_DOWNLOAD_COMPLETE;

public class DownloadReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Objects.equals(intent.getAction(), ACTION_DOWNLOAD_COMPLETE)){
            checkDownloadStatus(context);
        }
    }


    //检查下载状态
    private void checkDownloadStatus(Context context) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();
        long downloadTaskId = SharePreferencesUtils.readLongSharedPreferences(context, "DOWNLOAD_TASK_ID");
        String downloadVersionName = SharePreferencesUtils.readStringSharedPreferences(context, "DOWNLOAD_VERSION_NAME");
        query.setFilterById(downloadTaskId);//筛选下载任务，传入任务ID，可变参数
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    LogUtils.logout(">>>下载暂停");
                case DownloadManager.STATUS_PENDING:
                    LogUtils.logout(">>>下载延迟");
                case DownloadManager.STATUS_RUNNING:
                    LogUtils.logout(">>>正在下载");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    LogUtils.logout(">>>下载完成");
                    //下载完成安装APK
                    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + downloadVersionName+".apk";
                    LogUtils.logout("install : "+downloadPath);
                    installAPK(context, new File(downloadPath));
                    break;
                case DownloadManager.STATUS_FAILED:
                    LogUtils.logout(">>>下载失败");
                    break;
            }
        }
    }

    //下载到本地后执行安装
    protected void installAPK(Context context, File file) {
        if (!file.exists()) return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://" + file.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        //在服务中开启activity必须设置flag,后面解释
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
